package cn.huaqingcheng.tool.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 保存当前进程的PID
 */
@SuppressWarnings("unused")
public interface PidTool {

    String PID = "pid";

    /**
     * 执行此方法时在当前目录 pid 文件中保存当前进程PID, <br>
     * 当虚拟机关闭时, pid 文件会自动清理
     *
     * @see #PID
     * @see File#deleteOnExit()
     */
    static void save() {
        save(PID);
    }

    static void save(String fileName) {
        File file = new File(fileName);
        long pid = ProcessHandle.current().pid();
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(String.valueOf(pid).getBytes(StandardCharsets.UTF_8));
            fos.flush();
            file.deleteOnExit();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
